<template>
  <div class="chat-container">
    <!-- 侧边栏：会话列表 -->
    <div class="sidebar" :class="{ collapsed: sidebarCollapsed }">
      <div class="sidebar-header">
        <h2 v-if="!sidebarCollapsed">对话历史</h2>
        <el-button
          circle
          :icon="sidebarCollapsed ? 'Expand' : 'Fold'"
          @click="toggleSidebar"
        />
      </div>

      <div class="sidebar-content" v-if="!sidebarCollapsed">
        <el-button
          type="primary"
          class="new-chat-btn"
          :icon="'Plus'"
          @click="createNewSession"
        >
          新建对话
        </el-button>

        <div class="session-list">
          <div
            v-for="session in sessions"
            :key="session.id"
            class="session-item"
            :class="{ active: session.id === currentSessionId }"
            @click="switchSession(session.id)"
          >
            <div class="session-title">{{ session.title }}</div>
            <div class="session-time">{{ formatRelativeTime(session.updatedAt) }}</div>
            <el-button
              class="delete-btn"
              :icon="'Delete'"
              size="small"
              text
              @click.stop="deleteSessionConfirm(session.id)"
            />
          </div>

          <el-empty
            v-if="sessions.length === 0"
            description="暂无对话记录"
            :image-size="80"
          />
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 顶部导航栏 -->
      <div class="top-bar">
        <div class="top-bar-title">
          <h1>{{ currentSession?.title || 'MedMOE' }}</h1>
        </div>
        <div class="top-bar-actions">
          <el-button :icon="'Compass'" @click="goToExplore">探索发现</el-button>
          <el-button :icon="'UserFilled'" @click="goToExperts">专家团队</el-button>
          <el-button :icon="'User'" @click="goToProfile">个人中心</el-button>
          <el-dropdown @command="handleUserCommand">
            <el-avatar :src="userStore.userInfo?.avatar" :icon="'UserFilled'" />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item disabled>
                  {{ userStore.userInfo?.username }}
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 消息区域 -->
  <div class="message-area" :class="{ empty: messages.length === 0 }" ref="messageAreaRef">
        <div v-if="messages.length === 0" class="welcome-container">
          <div class="welcome-message">
            <div class="welcome-content">
              <h2>👋 您好！我是您的健康助手</h2>
              <p>有任何健康问题都可以问我</p>
            </div>
          </div>
          <!-- 悬浮输入区域 -->
          <div class="floating-input-container">
            <div class="input-area floating">
              <el-input
                v-model="inputMessage"
                type="textarea"
                :rows="3"
                placeholder="输入您的问题..."
                :disabled="loading"
                @keydown.enter.exact.prevent="handleSend"
              />
              <el-button
                type="primary"
                :icon="'Promotion'"
                :loading="loading"
                :disabled="!inputMessage.trim()"
                @click="handleSend"
              >
                发送
              </el-button>
            </div>
          </div>
        </div>

        <div
          v-for="message in messages"
          :key="message.id"
          class="message-item"
          :class="message.role"
        >
          <div class="message-avatar">
            <el-avatar
              v-if="message.role === 'user'"
              :src="userStore.userInfo?.avatar"
              :icon="'UserFilled'"
            />
            <el-avatar v-else :icon="'ChatDotRound'" />
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            
            <!-- AI消息的扩展信息 -->
            <div v-if="message.role === 'assistant'" class="message-extras">
              <!-- 专家来源 -->
              <div v-if="message.experts && message.experts.length > 0" class="message-experts">
                <el-tag size="small" type="info">
                  <el-icon><Avatar /></el-icon>
                  <span>专家来源</span>
                </el-tag>
                <el-tooltip
                  v-for="expert in message.experts"
                  :key="expert.id"
                  :content="expert.title"
                  placement="top"
                >
                  <el-tag size="small" class="expert-tag">{{ expert.name }}</el-tag>
                </el-tooltip>
              </div>

              <!-- 推荐文章 -->
              <div v-if="message.articles && message.articles.length > 0" class="message-articles">
                <div class="articles-header">
                  <el-icon><Document /></el-icon>
                  <span>相关推荐</span>
                </div>
                <div class="articles-list">
                  <div
                    v-for="article in message.articles"
                    :key="article.id"
                    class="article-card"
                    @click="openArticle(article)"
                  >
                    <h4>{{ article.title }}</h4>
                    <p>{{ article.summary }}</p>
                    <el-icon class="article-arrow"><ArrowRight /></el-icon>
                  </div>
                </div>
              </div>

              <!-- 反馈按钮 -->
              <div class="message-feedback">
                <el-button
                  :icon="message.feedback === 'like' ? 'StarFilled' : 'Star'"
                  :type="message.feedback === 'like' ? 'primary' : 'default'"
                  size="small"
                  text
                  @click="handleFeedback(message.id, 'like')"
                >
                  有帮助
                </el-button>
                <el-button
                  :icon="message.feedback === 'dislike' ? 'CircleCloseFilled' : 'CircleClose'"
                  :type="message.feedback === 'dislike' ? 'danger' : 'default'"
                  size="small"
                  text
                  @click="handleFeedback(message.id, 'dislike')"
                >
                  无帮助
                </el-button>
                <el-button
                  :icon="'Collection'"
                  size="small"
                  text
                  @click="handleBookmark(message)"
                >
                  收藏
                </el-button>
              </div>
            </div>
            
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>

        <div v-if="loading" class="message-item assistant">
          <div class="message-avatar">
            <el-avatar :icon="'ChatDotRound'" />
          </div>
          <div class="message-content">
            <div class="message-loading">
              <span></span><span></span><span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area" v-if="messages.length > 0">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="输入您的问题..."
          :disabled="loading"
          @keydown.enter.exact.prevent="handleSend"
        />
        <el-button
          type="primary"
          :icon="'Promotion'"
          :loading="loading"
          :disabled="!inputMessage.trim()"
          @click="handleSend"
        >
          发送
        </el-button>
      </div>

      <!-- 推荐区域 -->
  <div class="recommend-area" v-if="recommendations.length > 0 && messages.length === 0">
        <h3>💡 为您推荐</h3>
        <div class="recommend-list">
          <div
            v-for="rec in recommendations"
            :key="rec.id"
            class="recommend-card"
            @click="applyRecommendation(rec)"
          >
            <div class="recommend-icon">{{ rec.icon }}</div>
            <div class="recommend-content">
              <div class="recommend-title">{{ rec.title }}</div>
              <div class="recommend-desc">{{ rec.description }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/stores/user';
import { useSessionStore } from '@/stores/session';
import { sendMessage, createSession, deleteSession as deleteSessionApi, getSessions } from '@/api/chat';
import { getRecommendations } from '@/api/recommendation';
import { formatRelativeTime, formatTime, generateId } from '@/utils/format';
import type { Message, Session } from '@/types/chat';
import type { Recommendation } from '@/types/api';

const router = useRouter();
const userStore = useUserStore();
const sessionStore = useSessionStore();

const sidebarCollapsed = ref(false);
const messageAreaRef = ref<HTMLElement>();
const inputMessage = ref('');
const loading = ref(false);
const messages = ref<Message[]>([]);
const currentSessionId = ref<string | null>(null);
const recommendations = ref<Recommendation[]>([]);

const sessions = computed(() => sessionStore.sessions);
const currentSession = computed(() => 
  sessions.value.find(s => s.id === currentSessionId.value)
);

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value;
};

// 创建新会话
const createNewSession = async () => {
  try {
    const response = await createSession('新对话');
    if (response.code === 200) {
      const newSession: Session = {
        id: response.data.sessionId,
        title: response.data.title,
        messages: [],
        createdAt: response.data.createdAt,
        updatedAt: response.data.createdAt
      };
      sessionStore.addSession(newSession);
      switchSession(newSession.id);
      ElMessage.success('创建成功');
    }
  } catch (error: any) {
    ElMessage.error('创建失败');
  }
};

// 切换会话
const switchSession = (sessionId: string) => {
  currentSessionId.value = sessionId;
  sessionStore.setActiveSession(sessionId);
  const session = sessions.value.find(s => s.id === sessionId);
  if (session) {
    messages.value = session.messages || [];
    scrollToBottom();
  }
};

// 删除会话确认
const deleteSessionConfirm = async (sessionId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await deleteSessionApi(sessionId);
    if (response.code === 200) {
      sessionStore.removeSession(sessionId);
      if (currentSessionId.value === sessionId) {
        currentSessionId.value = sessions.value[0]?.id || null;
        if (currentSessionId.value) {
          switchSession(currentSessionId.value);
        } else {
          messages.value = [];
        }
      }
      ElMessage.success('删除成功');
    }
  } catch (error) {
    // 用户取消
  }
};

// 发送消息
const handleSend = async () => {
  if (!inputMessage.value.trim() || loading.value) return;

  // 确保有当前会话
  if (!currentSessionId.value) {
    await createNewSession();
    if (!currentSessionId.value) return;
  }

  const content = inputMessage.value.trim();
  inputMessage.value = '';

  // 添加用户消息
  const userMessage: Message = {
    id: generateId('msg'),
    sessionId: currentSessionId.value,
    role: 'user',
    content,
    timestamp: Date.now(),
    status: 'sending'
  };
  messages.value.push(userMessage);
  scrollToBottom();

  loading.value = true;

  try {
    const response = await sendMessage({
      sessionId: currentSessionId.value,
      content
    });

    if (response.code === 200) {
      // 添加AI回复(包含扩展信息)
      const aiMessage: Message = {
        id: response.data.messageId,
        sessionId: currentSessionId.value,
        role: 'assistant',
        content: response.data.content,
        timestamp: response.data.timestamp,
        status: 'success',
        // 模拟专家来源和推荐文章
        experts: response.data.experts || [
          { id: 'e1', name: '张医生', title: '心血管专家' },
          { id: 'e2', name: '李医生', title: '营养科主任' }
        ],
        articles: response.data.articles || [
          {
            id: 'a1',
            title: '如何科学降血压',
            summary: '通过饮食、运动和生活方式的调整来控制血压',
            url: 'https://example.com/article1'
          },
          {
            id: 'a2',
            title: '高血压患者的饮食指南',
            summary: '详细的高血压患者饮食建议和注意事项',
            url: 'https://example.com/article2'
          }
        ]
      };
      messages.value.push(aiMessage);

      // 更新会话
      sessionStore.updateSession(currentSessionId.value, {
        messages: messages.value,
        updatedAt: Date.now(),
        lastMessage: response.data.content.substring(0, 50) + '...'
      });

      // 获取推荐
      loadRecommendations();
    }
  } catch (error: any) {
    ElMessage.error('发送失败');
  } finally {
    loading.value = false;
    scrollToBottom();
  }
};

// 应用推荐
const applyRecommendation = (rec: Recommendation) => {
  if (rec.action) {
    inputMessage.value = rec.action;
  }
};

// 加载推荐
const loadRecommendations = async () => {
  try {
    const response = await getRecommendations();
    if (response.code === 200) {
      recommendations.value = response.data.recommendations;
    }
  } catch (error) {
    console.error('加载推荐失败', error);
  }
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (messageAreaRef.value) {
    messageAreaRef.value.scrollTop = messageAreaRef.value.scrollHeight;
  }
};

// 跳转到探索发现
const goToExplore = () => {
  router.push('/explore');
};

// 跳转到专家介绍
const goToExperts = () => {
  router.push('/experts');
};

// 跳转到个人中心
const goToProfile = () => {
  router.push('/profile');
};

// 用户操作
const handleUserCommand = (command: string) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      userStore.logout();
      sessionStore.clearSessions();
      router.push('/login');
    }).catch(() => {});
  }
};

// 打开文章
const openArticle = (article: any) => {
  if (article.url) {
    window.open(article.url, '_blank');
  } else {
    ElMessage.info('文章链接暂不可用');
  }
};

// 处理反馈
const handleFeedback = (messageId: string, feedbackType: 'like' | 'dislike') => {
  const message = messages.value.find(m => m.id === messageId);
  if (message) {
    // 如果已经是相同的反馈,则取消
    if (message.feedback === feedbackType) {
      message.feedback = undefined;
      ElMessage.info('已取消反馈');
    } else {
      message.feedback = feedbackType;
      ElMessage.success(feedbackType === 'like' ? '感谢您的反馈！' : '我们会努力改进');
    }
    
    // TODO: 调用API保存反馈
    // await saveFeedback(messageId, feedbackType);
  }
};

// 收藏消息
const handleBookmark = (message: Message) => {
  ElMessage.success('已添加到收藏');
  // TODO: 调用API保存收藏
  // await addBookmark({
  //   title: '来自对话的收藏',
  //   content: message.content,
  //   source: 'AI对话',
  //   category: '健康咨询',
  //   tags: []
  // });
};

// 初始化
onMounted(async () => {
  // 加载会话列表
  try {
    const response = await getSessions();
    if (response.code === 200) {
      sessionStore.setSessions(response.data.sessions.map(s => ({
        id: s.id,
        title: s.title,
        messages: [],
        createdAt: s.createdAt,
        updatedAt: s.updatedAt,
        lastMessage: s.lastMessage
      })));
    }
  } catch (error) {
    console.error('加载会话失败', error);
  }

  // 如果有会话，加载第一个
  if (sessions.value.length > 0) {
    switchSession(sessions.value[0].id);
  }

  // 加载推荐
  loadRecommendations();
});

// 监听消息变化，自动滚动
watch(messages, () => {
  scrollToBottom();
}, { deep: true });
</script>

<style scoped lang="scss">
.chat-container {
  display: flex;
  height: 100vh;
  background: #f5f7fa;
}

// 侧边栏样式
.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  transition: width 0.3s;

  &.collapsed {
    width: 60px;
  }

  .sidebar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e4e7ed;

    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }

  .sidebar-content {
    flex: 1;
    overflow-y: auto;
    padding: 20px;

    .new-chat-btn {
      width: 100%;
      margin-bottom: 20px;
    }

    .session-list {
      .session-item {
        padding: 12px;
        border-radius: 8px;
        cursor: pointer;
        margin-bottom: 8px;
        position: relative;
        transition: background 0.2s;

        &:hover {
          background: #f5f7fa;

          .delete-btn {
            opacity: 1;
          }
        }

        &.active {
          background: #ecf5ff;
        }

        .session-title {
          font-size: 14px;
          font-weight: 500;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .session-time {
          font-size: 12px;
          color: #909399;
        }

        .delete-btn {
          position: absolute;
          top: 8px;
          right: 8px;
          opacity: 0;
          transition: opacity 0.2s;
        }
      }
    }
  }
}

// 主内容区样式
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;

  .top-bar {
    height: 60px;
    background: white;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;

    .top-bar-title h1 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }

    .top-bar-actions {
      display: flex;
      align-items: center;
      gap: 12px;
    }
  }

  .message-area {
    flex: 1;
    overflow-y: auto;
    padding: 20px;

    &.empty {
      /* 当没有消息时显示欢迎布局 */
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: center;
      padding: 0;
      min-height: 200px;
    }

    .welcome-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 100%;
      padding-top: 120px; /* 顶部留白，让整个内容悬浮 */
    }

    .welcome-message {
      text-align: center;
      color: #909399;
      margin-bottom: 60px; /* 与输入区域保持更大距离 */

      .welcome-content {
        padding: 40px 20px;
        
        h2 {
          font-size: 24px;
          margin-bottom: 10px;
        }

        p {
          font-size: 16px;
        }
      }
    }

    .floating-input-container {
      width: 100%;
      max-width: 800px;
      margin: 0 auto;
    }
  }

  .message-item {
    display: flex;
    margin-bottom: 20px;

    &.user {
      flex-direction: row-reverse;

      .message-content {
        align-items: flex-end;
        margin-right: 12px;
      }

      .message-text {
        background: #409eff;
        color: #000000; /* 黑色文字，确保在蓝色背景上可见 */
      }
    }

    &.assistant {
      .message-content {
        margin-left: 12px;
      }
    }

    .message-avatar {
      flex-shrink: 0;
    }

    .message-content {
      display: flex;
      flex-direction: column;
      max-width: 70%;

      .message-text {
        padding: 14px 18px;
        border-radius: 16px; /* 现代化圆角 */
        background: white;
        line-height: 1.6;
        white-space: pre-wrap;
        word-break: break-word;
        box-shadow: 0 6px 18px rgba(16,24,40,0.05); /* 现代化阴影 */
        border: none; /* 无边框设计 */
        transition: all 0.2s ease;
      }

      .message-extras {
        margin-top: 16px;
        padding-top: 16px;
        border-top: 1px solid #f0f0f0;
        
        .message-experts {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 12px;
          flex-wrap: wrap;
          
          .expert-tag {
            cursor: pointer;
            transition: all 0.2s;
            
            &.user {
              flex-direction: row-reverse;

              .message-content {
                align-items: flex-end;
                margin-right: 12px;
              }

              .message-text {
                /* 现代化用户气泡：蓝色渐变 + 白字 */
                background: linear-gradient(135deg, #409eff 0%, #1f8fff 100%);
                color: #fff;
                box-shadow: 0 8px 24px rgba(64,158,255,0.12);
                border-radius: 16px; /* 统一圆角 */
                border: none; /* 无边框 */
              }
            }
            gap: 6px;
            font-size: 14px;
            font-weight: 500;
            color: #606266;
            margin-bottom: 8px;
          }
          
          .articles-list {
            display: flex;
            flex-direction: column;
            gap: 8px;
            
            .article-card {
              padding: 12px;
              background: #f9f9f9;
              border-radius: 6px;
              border: 1px solid #e4e7ed;
              cursor: pointer;
              transition: all 0.2s;
              position: relative;
              
              &:hover {
                border-color: #409eff;
                background: #ecf5ff;
                
                .article-arrow {
                  transform: translateX(4px);
                }
              }
              
              h4 {
                margin: 0 0 4px 0;
                font-size: 14px;
                font-weight: 500;
                color: #303133;
              }
              
              p {
                margin: 0;
                font-size: 12px;
                color: #909399;
                line-height: 1.4;
                padding-right: 24px;
              }
              
              .article-arrow {
                position: absolute;
                right: 12px;
                top: 50%;
                transform: translateY(-50%);
                color: #909399;
                transition: transform 0.2s;
              }
            }
          }
        }
        
        .message-feedback {
          display: flex;
          gap: 8px;
          
          .el-button {
            padding: 4px 8px;
          }
        }
      }

      .message-time {
        font-size: 12px;
        color: #909399;
        margin-top: 8px;
        padding: 0 4px;
      }

      .message-loading {
        padding: 12px 16px;
        background: rgba(255,255,255,0.9);
        border-radius: 12px;

        span {
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: #409eff;
          margin: 0 2px;
          animation: loading 1.4s infinite ease-in-out both;

          &:nth-child(1) {
            animation-delay: -0.32s;
          }

          &:nth-child(2) {
            animation-delay: -0.16s;
          }
        }
      }
    }
  }
}

  .input-area {
    padding: 20px;
    background: white;
    border-top: 1px solid #e4e7ed;
    display: flex;
    gap: 12px;

    &.floating {
      /* 悬浮模式：无边框，悬浮在欢迎文字下方 */
      border-top: none;
      background: transparent;
      position: relative;
      z-index: 10;
      padding: 0;
      margin: 0;
    }

    :deep(.el-textarea__inner) {
      resize: none;
      border-radius: 16px; /* 现代化圆角 */
      border: 1px solid #e4e7ed;
      padding: 12px 16px;
      font-size: 14px;
      line-height: 1.5;
      color: #000000; /* 黑色文字 */
      transition: all 0.2s ease;
      
      &:focus {
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
      }
    }

    .el-button {
      height: auto;
      min-height: 48px;
      border-radius: 16px; /* 现代化圆角 */
      padding: 12px 32px;
      font-weight: 600;
      font-size: 16px;
      transition: all 0.2s ease;
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
      }
      
      &:active {
        transform: translateY(0);
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
      }
    }
  }

  .recommend-area {
    padding: 20px;
    background: white;
    border-top: 1px solid #e4e7ed;

    h3 {
      margin: 0 0 16px 0;
      font-size: 16px;
      font-weight: 600;
    }

    .recommend-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 12px;

      .recommend-card {
        padding: 16px;
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s;
        display: flex;
        gap: 12px;

        &:hover {
          border-color: #409eff;
          box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
        }

        .recommend-icon {
          font-size: 24px;
          flex-shrink: 0;
        }

        .recommend-content {
          flex: 1;

          .recommend-title {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 4px;
        }

          .recommend-desc {
            font-size: 12px;
            color: #909399;
            line-height: 1.4;
          }
        }
      }
    }
  }


@keyframes loading {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    z-index: 1000;
    transform: translateX(-100%);

    &:not(.collapsed) {
      transform: translateX(0);
    }
  }

  .message-area .message-item .message-content {
    max-width: 85%;
  }
}
</style>